//
//  WQMqttManager.m
//  MqttTest
//
//  Created by 魏强 on 16/12/29.
//  Copyright © 2016年 魏强. All rights reserved.
//

#import "WQMqttManager.h"

@interface WQMqttManager (){
    
}

@property (strong, nonatomic) NSDictionary *mqttSettings;
@property (strong, nonatomic) NSString *base;
@end
@implementation WQMqttManager
singleton_implementation(WQMqttManager)
-(void)connectToHost{
//    if (!self.manager) {
        [self setupMqttManager];
//    }
}
- (void)setupMqttManager{
    NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
    NSURL *mqttPlistUrl = [bundleURL URLByAppendingPathComponent:@"mqtt.plist"];
    self.mqttSettings = [NSDictionary dictionaryWithContentsOfURL:mqttPlistUrl];
    self.base = self.mqttSettings[@"base"];
    /*
     * MQTTClient: create an instance of MQTTSessionManager once and connect
     * will is set to let the broker indicate to other subscribers if the connection is lost
     */
//    KDLog(@"selfTopic:%@\n grandCompTopic:%@\n compTopic:%@\n",selfTopic, grandCompTopic,compTopic);
//    if (!self.manager) {
        self.manager = [[MQTTSessionManager alloc] init];
        self.manager.delegate = self;
        [self resetConnect];
//    } else {
//        [self.manager connectToLast];
//    }
}
/**
 *  <#Description#>
 */
- (void)resetConnect{
    KDAccount *account = [KDAccountTool account];

    NSString *selfTopic = [NSString stringWithFormat:@"kd/%@",account.subs_id];
    NSString *grandCompTopic = [NSString stringWithFormat:@"kd/%@/+/push",account.grand_comp_id];
    NSString *compTopic = [NSString stringWithFormat:@"kd/%@/+/push",account.subs_comp_id];

    self.manager.subscriptions = @{selfTopic:@2,grandCompTopic:@2, compTopic:@2};
    //        [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:MQTTQosLevelExactlyOnce]
    //                                                                 forKey:@"kd/comp000000100009/comp000000100012/subs000001000048"];//[NSString stringWithFormat:@"%@/#", self.base
    [self.manager connectTo:self.mqttSettings[@"host"]
                       port:[self.mqttSettings[@"port"] intValue]
                        tls:[self.mqttSettings[@"tls"] boolValue]
                  keepalive:60
                      clean:true
                       auth:true
                       user:@"mosquitto"
                       pass:@"Kdmqtt2016@"
                  willTopic:selfTopic
                       will:[@"offline" dataUsingEncoding:NSUTF8StringEncoding]
     
                    willQos:MQTTQosLevelExactlyOnce
             willRetainFlag:FALSE
               withClientId:nil];
}
- (void)disconnect{
    /*
     * MQTTClient: send goodby message and gracefully disconnect
     */
//    [self.manager sendData:[@"leaves chat" dataUsingEncoding:NSUTF8StringEncoding]
//                     topic:@"kd/comp000000100009/comp000000100012/subs000001000048"
//                       qos:MQTTQosLevelExactlyOnce
//                    retain:FALSE];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
//    if (self.manager.state == MQTTSessionManagerStateConnected) {
        [self.manager disconnect];
//    }
    
}

- (void)sendMessage:(NSString *)message{
    /*
     * MQTTClient: send data to broker
     */
    [self.manager sendData:[message dataUsingEncoding:NSUTF8StringEncoding]
                     topic:@"kd/subs000001000008"
                       qos:MQTTQosLevelExactlyOnce
                    retain:FALSE];
}

/*
 * MQTTSessionManagerDelegate
 */
- (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained {
    /*
     * MQTTClient: process received message
     */
        //    NSString *senderString = [topic substringFromIndex:self.base.length + 1];
    if (_delegate && [_delegate respondsToSelector:@selector(receiveData: ontopic:)]) {
        [_delegate receiveData:data ontopic:topic];
    }

}


@end
